package com.updesignsz.admin.controller;

import com.updesignsz.admin.service.BannerService;
import com.updesignsz.admin.util.ResponseUtil;
import com.updesignsz.admin.vo.form.BannerForm;
import com.updesignsz.commom.entity.Banner;
import com.updesignsz.commom.util.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

/**
 * 横幅图片
 * Creation date 2020-8-8 15:02:24
 */
@RestController
public class BannerController {

	@Autowired
	private BannerService bannerService;

	/**
	 * 横幅图片列表
	 */
	@GetMapping("/banner")
	public void insuranceBanner(Banner banner, HttpServletResponse response) {
		ResultVo vo = new ResultVo();
		vo.setData(bannerService.listAll(banner));
		ResponseUtil.outJson(vo.toJsonMsg(), response);
	}

	/**
	 * 保存 横幅图片
	 */
	@PostMapping("/banner")
	public void addBanner(@Validated(PostMapping.class) @RequestBody BannerForm form, HttpServletResponse response) {
		ResultVo vo = new ResultVo();
		Banner banner = convert(form);
		bannerService.saveBanner(banner);
		vo.setData(bannerService.getById(banner.getId()));
		ResponseUtil.outJson(vo.toJsonMsg(), response);
	}


	/**
	 * 删除 横幅图片
	 */
	@DeleteMapping("/banner/{bannerId}")
	public void deleteBanner(@PathVariable Integer bannerId, HttpServletResponse response) {
		ResultVo vo = new ResultVo();
		bannerService.deleteBanner(bannerId);
		ResponseUtil.outJson(vo.toJsonMsg(), response);
	}

	/**
	 * 修改 横幅图片
	 */
	@PutMapping("/banner")
	public void updateBanner(@Validated(PutMapping.class) @RequestBody BannerForm form, HttpServletResponse response) {
		ResultVo vo = new ResultVo();
		Banner banner = convert(form);
		bannerService.updateBanner(banner);
		vo.setData(bannerService.getById(banner.getId()));
		ResponseUtil.outJson(vo.toJsonMsg(), response);
	}


	private Banner convert(BannerForm bannerForm) {
		Banner banner = new Banner();
		banner.setId(bannerForm.getId());
		banner.setProjectId(bannerForm.getProjectId());
		banner.setType(bannerForm.getType());
//		banner.setImage(bannerForm.getImage());
//		String[] images = bannerForm.getImage().split(",");
//		if (images.length > 0) {
//			banner.setImageThumbnail(images[0].replace("uploads/", "uploads/thumb_"));
//		}
		return banner;
	}

}